/**
 * @Author: jipeng.Li
 * @Date: 2021-03-03 14:18:21
 * @LastEditors: jipeng.Li
 * @LastEditTime: 2021-03-03 14:18:21
 * @Description: 选择加油点列表
 */
import React, { Component } from 'react';
import {
  SafeAreaView,
  StyleSheet,
  View,
  NativeModules
} from 'react-native';
import {
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp
} from '@/styles';
import { empty02 } from '@/image';
import oilApi from '@/api/oil';
import { msg } from '@/common';
import oil from '@/api/oil';
import XmList from '../../../components/XmList';
import OrtherOilStationItem from './components/orther-oil-station-item';
import ResetPosition from './components/reset-position';
import OilStationItem from './components/oil-station-item';
import EmptyPage from '../../../components/EmptyPage';

export default class AddOilLocale extends Component {
  constructor(props) {
    super(props);
    this.state = {
      showFoot: 1,
      isLoading: false,
      pageNo: 1,
      pageSize: 15,
      stationList: [],
      longAndLat: {},
      address: null
    };
  }

  componentDidMount() {
    this.getCurrentPosition();
  }

  render() {
    const { showFoot, isLoading, stationList, address } = this.state;
    const currentAddress = stationList.length && stationList[0];
    return (
      <SafeAreaView style={styles.container}>
        {/* 定位油站 */}
        <View style={styles.currentServiceStation}>
          <OilStationItem
            name={currentAddress.siteName}
            address={currentAddress.address}
            isHeader={false}
            onPress={() => this.selectOilStation(currentAddress)}
          />
          <ResetPosition
            address={address && address.addressDetail}
            onPress={this.getCurrentPosition}
          />
        </View>
        <OrtherOilStationItem city={address && address.city} />
        <XmList
          sources={stationList}
          renderItem={this._renderItem}
          style={{ backgroundColor: mainBgColorWhite }}
          isLoading={isLoading}
          onDropdownRefresh={this.loadData}
          onPullUpMore={this.LoadMore}
          singleKey={item => `stationList${item.id}`}
          showFoot={showFoot}
          customEmptyView={<EmptyPage emptyIcon={empty02} noText='附近暂无油站~' />}
        />
      </SafeAreaView>
    );
  }

  _renderItem = (data) => {
    const { item } = data;
    return (
      <OilStationItem
        key={`oilStationItem${item.id}`}
        name={item.siteName}
        address={item.address}
        onPress={() => this.selectOilStation(item)}
      />
    );
  }

  // 下拉刷新
  loadData = () => {
    this.setState({
      isLoading: true,
      pageNo: 1,
      stationList: [],
      showFoot: 0
    }, () => {
      this.pageSite('pullDown');
    });
  }

  // 上拉加载更多
  LoadMore = () => {
    this.setState({ showFoot: 2 }, () => {
      this.pageSite('pullUp');
    });
  }

  // 获取当前定位
  getCurrentPosition = () => {
    NativeModules.MapModule.getCurrentPosition().then((resPosition) => {
      if (resPosition.city) {
        let longAndLat = { lat: resPosition.latitude, lgt: resPosition.longitude };
        this.setState({ longAndLat, address: resPosition }, () => this.loadData());
      } else {
        msg.emit('app:tip', { text: '获取地理位置信息失败' });
      }
    });
  };

  pageSite = (type) => {
    const { pageNo, pageSize, stationList, longAndLat } = this.state;
    let newStationList = [];
    oil.pageSite({ pageNo, pageSize, siteType: 2, ...longAndLat }).then(res => {
      if (res.success) {
        const { records, pages } = res.data;
        if (type === 'pullDown') {
          this.setState({ stationList: records });
        }
        if (type === 'pullUp') {
          if (pageNo > pages) {
            this.setState({ showFoot: 1 });
            return;
          }
          newStationList = [...stationList, ...records];
          this.setState({ stationList: newStationList });
        }
        this.setState({ isLoading: false, pageNo: pageNo + 1 });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  // 选择加油点
  selectOilStation = (curStation) => {
    if (curStation) {
      msg.emit('curStation', curStation);
      msg.emit('router: goToNext', {
        routeName: 'WriteOffForOil'
      });
    }
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  currentServiceStation: {
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(20),
  }
});
